package com.deuwise.system.controller;

import com.deuwise.common.utils.CreateVerifyCode;
import com.deuwise.common.utils.Result;
import com.deuwise.common.utils.cache.Cache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(description = "验证码接口")
@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    @RequestMapping(value = "/getVerifyCode", method = RequestMethod.GET)
    @ApiOperation(value = "获取验证码")
    public void drawCaptcha(HttpServletResponse response,HttpServletRequest request) throws IOException {

        // 得到验证码 生成指定验证码
        String code = new CreateVerifyCode().randomStr(4);
        String ip = request.getRemoteAddr();
        Cache.add(ip+"_VerifyCode",code,20000);
        CreateVerifyCode vCode = new CreateVerifyCode(116,36,4,10,code);
        vCode.write(response.getOutputStream());
    }
    @ApiOperation(value = "校验验证码")
    @RequestMapping(value = "/checkVerifyCode", method = RequestMethod.GET)
    public Result<String> checkVerifyCode(HttpServletResponse response,
                                  HttpServletRequest request, String code) {

        String ip = request.getRemoteAddr();
       Object object=Cache.get(ip+"_VerifyCode");
        String redisCode = (String)object;
        if (code != null && !"".equals(code) && redisCode != null && !"".equals(redisCode)) {
            if (code.equalsIgnoreCase(redisCode)) {
                Cache.remove(ip+"_VerifyCode");
               return  Result.ok();
            } else {
                return  Result.fail();
            }
        } else {
            return  Result.fail();
        }
    }

}
